﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Device.Location;
using Microsoft.Phone.Maps;
using Microsoft.Phone.Maps.Controls;
using Windows.Devices.Geolocation;

namespace Mapping_Demo
{
    public partial class SimpleDistance : PhoneApplicationPage
    {
        Geolocator geolocator;

        public SimpleDistance()
        {
            InitializeComponent();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            geolocator = new Geolocator();
            GetCurrentLocation();
            base.OnNavigatedTo(e);
        }

        private async void GetCurrentLocation()
        {
            try
            {
                geolocator.DesiredAccuracyInMeters = 50;
                // If the cached location is over 30 minutes old, get a new one
                TimeSpan maximumAge = new TimeSpan(0, 30, 0);
                // If we're trying for more than 45 seconds, abandon the operation
                TimeSpan timeout = new TimeSpan(0, 0, 5);
                Geoposition myLocation = await geolocator.GetGeopositionAsync(maximumAge, timeout);

                GeoCoordinate geoCord = new GeoCoordinate(myLocation.Coordinate.Latitude, myLocation.Coordinate.Longitude);
                distanceMap.Center = geoCord;
                distanceMap.ZoomLevel = 12;
            }
            catch (Exception exception)
            {
                //if this is an UnauthorizedAccessException:
                //      1) you haven’t included ID_CAP_LOCATION in your app manifest
                //      or
                //      2) user has disabled location in the phone Settings

                // if this is a TimeoutExceeded exception:
                //      the device couldn't get a location in the allotted time
            }

        }

        private GeoCoordinate startCoord = null;
        private Point originPoint;
        private GeoCoordinate currentCoord = null;
        private GeoCoordinate endCoord = null;
        
        private void StartNewDistance(object sender, System.Windows.Input.ManipulationStartedEventArgs e)
        {
            originPoint = e.ManipulationOrigin;
            startCoord= distanceMap.ConvertViewportPointToGeoCoordinate(originPoint);
            MapLayer newML = new MapLayer();
            MapOverlay moStart = new MapOverlay();
            moStart.Content = new LargeTouchPoint();
            moStart.GeoCoordinate = startCoord;
            MapOverlay moEnd = new MapOverlay();
            moEnd.Content = new LargeTouchPoint();
            moEnd.GeoCoordinate = startCoord;

            newML.Add(moStart);
            newML.Add(moEnd);

            distanceMap.Layers.Clear();
            distanceMap.Layers.Add(newML);

            distanceMap.MapElements.Clear();
            MapPolyline mp = new MapPolyline();
            mp.Path = new GeoCoordinateCollection();
            mp.Path.Add(startCoord);
            mp.Path.Add(startCoord);
            mp.StrokeThickness = 6;
            mp.StrokeColor = System.Windows.Media.Color.FromArgb(255, 166, 28, 28);
            distanceMap.MapElements.Add(mp);
        }

        private void updateDistance(object sender, System.Windows.Input.ManipulationDeltaEventArgs e)
        {
            Point currentPoint = new Point(originPoint.X + e.CumulativeManipulation.Translation.X, originPoint.Y + e.CumulativeManipulation.Translation.Y);
            currentCoord = distanceMap.ConvertViewportPointToGeoCoordinate(currentPoint);
            (distanceMap.Layers[0])[1].GeoCoordinate = currentCoord;

            // Gets the distance in meters
            double distance = currentCoord.GetDistanceTo(startCoord);
            // Sample
            GeoCoordinate newCoord = new GeoCoordinate(40.8, -73.9);
            double alertDistance = newCoord.GetDistanceTo(new GeoCoordinate(40.801, -73.901));
            MessageBox.Show((alertDistance/1000).ToString());

            double distanceInMiles = distance * .000621371;
            if (distanceInMiles < .2)
            {
                double distanceInFeet = distance * 3.28084;
                distanceText.Text = string.Format("{0:N0}", distanceInFeet) + " feet";
            }
            else
            {
                distanceText.Text = string.Format("{0:N1}", distanceInMiles) + " miles";
            }
            ((MapPolyline)distanceMap.MapElements[0]).Path[1] = currentCoord;
        }

        private void finalizeDistance(object sender, System.Windows.Input.ManipulationCompletedEventArgs e)
        {

        }

        private void StartDistanceCalc(object sender, System.Windows.Input.GestureEventArgs e)
        {
            if (borderSpace.Visibility == Visibility.Visible)
            {
                distanceText.Text = "tap here to calculate distance";
                borderSpace.Visibility = Visibility.Collapsed;
                //distanceMap.Layers.Clear();
                //distanceMap.MapElements.Clear();
            }else{
                borderSpace.Visibility = Visibility.Visible;
                distanceText.Text = "tap and drag the map";
            }
        }
    }
}